package com.sample.plove.authener.wecontroll;

import com.sample.plove.authener.config.WechatConfig;
import com.sample.plove.authener.model.BasicAuthParam;
import com.sample.plove.authener.model.response.AccessToken;
import com.sample.plove.authener.model.response.AuthAccessToken;
import com.sample.plove.authener.model.response.AuthUserInfo;
import com.sample.plove.authener.server.WechatAuthService;
import com.sample.plove.authener.server.impl.WechatAuthServiceImpl;
import com.sample.plove.authener.util.WechatCheckSignature;
import com.sample.plove.authener.util.WechatUtil;
import com.sample.plove.database.model.AccessTokenEntity;
import com.sample.plove.database.service.AccessToeknServer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * PackageName:com.sample.plover.controller
 * Author:Administrator
 * Time:22:41
 * Date:2019/4/25
 * Describe:
 */
@Controller
@RequestMapping("we")
public class WechatController {
    @Value("test")
    private String DNBX_TOKEN;
    @Autowired
    private AccessToeknServer accessToeknServer;
    @Autowired
    private WechatAuthService authService;
    private static final Logger log = LoggerFactory.getLogger("WechatController");
    private String openid = "";
    private String code = "";
    private String token = "";

    @RequestMapping(value = "check", method = {RequestMethod.GET})
    @ResponseBody
    public void connectWeiXin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        try {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");

            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (WechatCheckSignature.checkSignature(DNBX_TOKEN, signature, timestamp, nonce)) {
                response.getWriter().write(echostr);
                System.out.println("微信校验成功");
            } else {
                System.out.println("校验失败");
            }
        } catch (Exception e) {
            System.out.println("校验异常" + e.getMessage());
        } finally {
            out.close();
        }
    }


    @RequestMapping(value = "getAccessToken", method = RequestMethod.GET)
    public AccessToken getAccessToken() {
        AccessToken accessToken = new AccessToken();
        AccessTokenEntity entity = accessToeknServer.findAccessTokenById(7).get();
        int in = entity.getExpiresIn();
        Long time = Long.valueOf(entity.getCreateDate());
        if ((System.currentTimeMillis() - time) / 1000 < in) {
            // 有效无需创建
            accessToken.setAccessToken(entity.getAccessToken());
            accessToken.setExpiresIn(entity.getExpiresIn());
            log.info("有效无需创建:", accessToken.toString());
            return accessToken;
        } else {
            // 无效重新获取
            WechatAuthService wechatAuthService = new WechatAuthServiceImpl();
            accessToken = wechatAuthService.getAccessToken();
            entity.setCreateDate(String.valueOf(System.currentTimeMillis()));
            entity.setAccessToken(accessToken.getAccessToken());
            entity.setExpiresIn(accessToken.getExpiresIn());
            entity.setId(7);
            accessToeknServer.updateAccessToken(entity);
            log.info("无需重新获取:", accessToken.toString());
            return accessToken;
        }
    }

    @RequestMapping(value = "resultCode", method = RequestMethod.GET)
    public String redirectUri(HttpServletRequest request) {
        if (StringUtils.isNoneEmpty(request.getParameter("code"))) {
            code = request.getParameter("code");
            log.info(code);
        }

        if (StringUtils.isNoneEmpty(request.getParameter("state"))) {
            String state = request.getParameter("state");
            log.info(state);
        }

        return code;
    }

    @RequestMapping(value = "getAuthAccessToken",method = RequestMethod.GET)
    public void getAuthAccessToken() {
        AuthAccessToken accessToken = WechatUtil.getAuthAccessToken(authService, code);
        if (accessToken != null) {
            log.info(accessToken.toString());
            if (StringUtils.isNoneEmpty(accessToken.getOpenid())) {
                openid = accessToken.getOpenid();
            }
            if (StringUtils.isNoneEmpty(accessToken.getRefreshToken())) {
                token = accessToken.getRefreshToken();
            }
        }
    }

    @RequestMapping(value = "getUserInfo",method = RequestMethod.GET)
    public void getUserInfo() {
        AuthUserInfo userInfo = WechatUtil.getAuthUserInfo(authService, token, openid);
        if (userInfo != null) {
            log.info(userInfo.toString());
        }
    }
}
